/* eslint no-constant-condition: ["error", { "checkLoops": false }] */
/**
 *
 * Copyright 2016-present scrm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import { put, take, call, fork } from 'redux-saga/effects';

import * as types from '../constants/ActionTypes';
import ToastUtil from '../utils/ToastUtil';
import RequestXhrUtil from '../utils/RequestXhrUtil';
import { SCRM_API } from '../constants/Urls';
import { UA } from '../utils/AttachParamsUtil';
import { 
  postSaveNoticeDevice, 
  receiveSaveNoticeDevice
} from '../actions/noticeDevice';


export function* saveNoticeDevice(
  token,
  site_id,
  deviceData
) {
  try {
    console.log(`${SCRM_API}/sites/${site_id}users/${token}/notice_device`, token, site_id, deviceData)
    yield put(postSaveNoticeDevice());
    const ndResponse = yield call(
      RequestXhrUtil.request,
      `${SCRM_API}/sites/${site_id}/users/${token}/notice_device`,
      'post',
      UA(deviceData)
    );
    yield put(receiveSaveNoticeDevice(
      ndResponse.results
    ));
    const errorMessage = ndResponse.errmsg;
    if (ndResponse.errcode) {
      yield ToastUtil.showShort(errorMessage);
    }
  } catch (error) { 
    console.log(error, 'error')
    yield put(receiveSaveNoticeDevice(null));
    ToastUtil.showShort('网络发生错误，请重试');
  }
}

export function* watchSaveNoticeDevice() {
  while (true) {
    const {
      token,
      site_id,
      deviceData
    } = yield take(types.SAVE_NOTICE_DEVICE);
    yield fork(
      saveNoticeDevice,
      token,
      site_id,
      deviceData
    );
  }
}
